<template>
    <div class="app-container">
        <div class="dialog-box">
            <el-dialog class="dialog" v-model="visible" title="网上支付查询" top="80px" draggable overflow
                :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
                <template #header="{ close, titleId, titleClass }">
                    <div class="my-header">
                        <h4 :id="titleId" :class="titleClass">网上支付查询</h4>
                        <el-button class="close-btn" @click="handleCancelDialog">
                            关闭
                        </el-button>
                    </div>
                </template>

                <el-form class="search-form" inline :model="searchForm">
            <div class="search-form-hang">
                <el-form-item class="search-form-item" label="交易单号:">
                    <el-input v-model="searchForm.tradeNo" placeholder="请输入交易单号" clearable />
                </el-form-item>
                <el-form-item class="search-form-item" label="桌台号:" >
                    <el-input v-model="searchForm.roomName" placeholder="请选择桌台号" @click="allTableSelectShow = true" clearable />
                </el-form-item>
                <el-form-item class="search-form-item" label="结账单号:" >
                    <el-input v-model="searchForm.payBatchCode" placeholder="请输入结账单号" clearable />
                </el-form-item>
                
                <el-form-item class="search-form-item" label="支付流水号:" >
                    <el-input v-model="searchForm.payItemCode" placeholder="请输入支付流水号" clearable />
                </el-form-item>
                
            </div>
            <div class="search-form-hang">
                <el-form-item class="search-form-item search-form-wd1" label="台单号:">
                    <el-input   v-model="searchForm.consumeCode" placeholder="请输入台单号" clearable />
                </el-form-item>
                <el-form-item class="search-form-item" label="交易类型:" >
                    <el-select v-model="searchForm.opType" filterable clearable placeholder="请选择交易类型"
                        @change="handleSearch()">
                        <el-option v-for="item in tradeType_options" :key="item.code" :value="item.code"
                            :label="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item class="search-form-item" label="支付方式:">
                    <el-select v-model="searchForm.payType" filterable clearable placeholder="请选择支付方式">
                        <el-option v-for="item in payType_options" :key="item.payCode" :value="item.payCode"
                            :label="item.payName" />
                    </el-select>
                </el-form-item>
                <el-form-item class="action-btn-box">
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button class="reset-btn" @click="handleReset">清空筛选</el-button>
                </el-form-item>
            </div>
            <div class="search-form-hang">
                <el-form-item class="search-form-item" label="选择时间:">
                    <el-date-picker v-model="searchForm.operDate" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" clearable />
                </el-form-item>
                <el-form-item class="search-form-item range-item" label="金额区间:">
                    <el-input v-model="searchForm.minMoney" placeholder="请输入最小金额" clearable />-
                    <el-input v-model="searchForm.maxMoney" placeholder="请输入最大金额" clearable />
                </el-form-item>
                
            </div>
        </el-form>
                <div class="table-box">
                    <el-table :data="tableData" stripe v-loading="loading">
                        <el-table-column type="index" label="序号" :min-width="orderColumnWidth" />
                        <el-table-column prop="roomName" label="房台号" :min-width="tableColumnWidth" />
                        <el-table-column prop="consumeCode" label="台单号" :min-width="tableColumnWidth" />
                        <el-table-column v-if="searchForm.opType != 2" prop="payMoney" label="支付金额" :min-width="orderColumnWidth">
                            <template #default="scope">
                                <!-- scope.row.opType == 2 ? '-' : -->
                                <span class="color-FF6A00">{{ scope.row.payMoney }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="crDate" label="交易时间" :min-width="tableColumnWidth" />
                        <el-table-column prop="payTypeName" label="支付方式" :min-width="orderColumnWidth" />
                        <el-table-column prop="tradeNo" label="交易号" :min-width="tableColumnWidth" />
                        
                       
                        <el-table-column prop="payItemCode" label="支付流水号" :min-width="tableColumnWidth" />
                        <el-table-column prop="opTypeName" label="交易类型" :min-width="orderColumnWidth" />
                        <!-- v-if="searchForm.opType != 2" -->

                        <el-table-column prop="totalRefundFee" label="已退金额" :min-width="orderColumnWidth">
                            <template #default="scope">
                                {{ scope.row.totalRefundFee }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="canRefundFee" label="可退金额" :min-width="orderColumnWidth">
                            <template #default="scope">
                                {{ (scope.row.opTypeName == '支付' && scope.row.tradeStateDesc == '支付成功') ||
                                    scope.row.tradeStateDesc
                                    == '退款成功' ? scope.row.canRefundFee : "-" }}
                            </template>
                        </el-table-column>
                        <!-- v-if="searchForm.opType == 2" -->
                        <el-table-column v-if="searchForm.opType == 2" prop="payMoney" label="退款金额" :min-width="orderColumnWidth">
                            <template #default="scope">
                                <span>{{ scope.row.opType == 2 ? scope.row.payMoney : '-' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="tradeStateDesc" label="状态" :min-width="orderColumnWidth" />
                        <el-table-column prop="operUser" label="操作人" :min-width="orderColumnWidth" />
                        <el-table-column prop="" label="操作" :min-width="orderColumnWidth" fixed="right">
                            <template #default="scope">
                                <div style="display: flex;">
                                    <el-button
                                    v-if="scope.row.opTypeName == '支付' || scope.row.opTypeName == '充值' && scope.row.tradeStateDesc == '支付成功'"
                                    class="action-btn" @click="handleReturn(scope.row)"> 退款</el-button>
                                    <el-button v-if="scope.row.tradeStateDesc !=='退款成功'" class="action-btn" @click="handleSubCode(scope.row)">确认</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- <div class="pagination-box">
            <el-pagination background layout="prev, pager, next,sizes, jumper, total" :total="total" :current-page.sync="currentPage"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top:10px" />
        </div> -->
                <div class="orderRecords-container-footer">
                    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page.sync="currentPage" :page-size="pageSize"
                        layout="total, prev, pager, next,sizes, jumper" :total="total">
                    </el-pagination>
                    <button class="footer-button">确定</button>
                </div>
            </el-dialog>
        </div>
    </div>
    <div class="return-dialog">
        <!-- 退款弹窗 -->
        <el-dialog class="dialog" title="退款" v-model="visible_return" top="80px" draggable :show-close="false"
            :close-on-click-modal="false" :before-close="handleCancel">
            <template #header="{ close, titleId, titleClass }">
                <div class="my-header">
                    <h4 :id="titleId" :class="titleClass">退款</h4>
                    <!-- <el-button class="close-btn" @click="handleCancel">关闭</el-button> -->
                </div>
            </template>
            <el-form class="class-form" :model="form" label-width="auto" size="large">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="可退金额：" prop="salaAmt">
                            {{ form.canRefundFee }}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="退款金额：" prop="salaAmt">
                            <el-input-number class="input-number" v-model="form.refundFee" :min="0" :max="max"
                                :controls="false" placeholder="请输入退款金额" clearable style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注：" prop="remark">
                            <el-input class="input-number" v-model="form.remark" placeholder="请输入备注" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="footer-box">
                <el-button class="cancel" @click="handleCancel" :disabled="submitloading">取消</el-button>
                <el-button class="submit" @click="handleSubmit" :disabled="submitloading">确认</el-button>
            </div>
        </el-dialog>
    </div>
    <AllTableSelect v-model="allTableSelectShow" @cancel="allTableSelectShow = false" @confirm="selectTable" />
</template>
  
<script setup>

import Api from '@/api'
import { ref } from 'vue';

import { transformWorkTime } from '@/utils/chenhao.js'
import useConfigStore from '@/store/config'
import AllTableSelect from '@/views/components/AllTableSelect.vue'
import ls from '@/lib/ls'

const configStore = useConfigStore()
const orgStartTime = configStore.shopInfo.orgReportStartTime //orgStartTime
const orgEndTime = configStore.shopInfo.orgReportEndTime //orgEndTime 
const router = useRouter()

const props = defineProps({
    visible: {
        type: Boolean,
        required: false,
    },
    consumeCode: {
        type: String,
        required: false,
        default: ""
    },
    payItemCode: {
        type: String,
        required: false,
        default: ""
    },
    jhcode:{
        type: Boolean,
        required: false,
    },
    unpay:{
        type: String,
        required: false,
    }
})

const unpay = toRef(props, 'unpay')

const tableColumnWidth = ref('280')
const orderColumnWidth = ref('140')
console.log(window.innerWidth,'window.innerWidth----------------');
window.addEventListener("resize",readerSize)
function readerSize (){
    console.log(window.innerWidth,'window.innerWidth2222222');
    if(window.innerWidth >= 1200){
        tableColumnWidth.value = '200'
        orderColumnWidth.value = '100'
    }else if(window.innerWidth >= 800 && window.innerWidth < 1200){
        tableColumnWidth.value = '160'
        orderColumnWidth.value = '80'
    }else if(window.innerWidth >= 400 && window.innerWidth < 800){
        tableColumnWidth.value = '80'
        orderColumnWidth.value = '40'
    } 
}


const visible = toRef(props, 'visible')
const consumeCode = toRef(props, 'consumeCode')
const payItemCode = toRef(props, 'payItemCode')
const jhcode = toRef(props, 'jhcode')
console.log(jhcode.value,'jhcode')
console.log('consumeCode.value :>> ', consumeCode.value);
console.log('payItemCode.value :>> ', payItemCode.value);
// 获取支付方式OPTIONS
let payType_options = ref([])
const get_payType_options = (params) => {
    // 支付类型 1:微信 2:支付宝
    payType_options = [
        { payCode: 1, payName: '微信' },
        { payCode: 2, payName: '支付宝' }
    ]
    return
    Api.Common.PcObjProcess.Do({ "functionName": "getPayType", "orgCode": "0004", "contentData": { parentCode: '571' } }).then(res => {
        console.log('获取支付方式OPTIONS res :>> ', res,);
        res.result.forEach(item => {
            if (item.payName == '微信' || item.payName == '支付宝') {
                payType_options.value.push(item)
            }
        });
    })
}
get_payType_options()

// 获取交易类型OPTIONS
let tradeType_options = ref([])
const get_tradeType_options = (params) => {
    // 1:支付 2:退款 3:充值
    tradeType_options.value = [
        { code: 1, name: '支付' },
        { code: 2, name: '退款' },
        { code: 3, name: '充值' }
    ]
}
get_tradeType_options()


let loading = ref(false)
let searchForm = ref({
    consumeCode: consumeCode.value,
    payItemCode: payItemCode.value,
    roomName:ls.get('payTableInfo')?.roomName,
    tradeNo: jhcode.value == true ? 'JH' : ''
})
// 搜索
const handleSearch = (params) => {
    currentPage.value = 1;
    getTableData();
}
// 重置
const handleReset = (params) => {
    searchForm.value = {}
    handleSearch()
}
// 查询表格数据
let tableData = ref([{}])
let currentPage = ref(1)
let pageSize = ref(7)
let total = ref(0)
const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getTableData()
}
const allTableSelectShow = ref(false)
// 选中桌台
const selectTable = (data) => {
    if (data.name) {
        console.log(data);
        searchForm.value.roomCode = data.code
        searchForm.value.roomName = data.name
        allTableSelectShow.value = false
    } else {
        ElNotification({
            title: '提示',
            message: '请选择桌号',
            type: 'warning',
        })
    }

}
const getTableData = (user) => {
    let query = {
        ...searchForm.value,
        pageIndex: currentPage.value,
        pageSize: pageSize.value
    }
    if (query.operDate && query.operDate.length > 1) {
        query.beginDate = query.operDate[0]
        query.endDate = query.operDate[1]
    }
    console.log('查询前的query :>> ', query,);
    loading.value = true
    // return
    Api.Common.PcObjProcess.Do({ "functionName": "GetPayOrderList", "orgCode": "0004", "contentData": query }).then(res => {
        console.log('查询订单table res :>> ', res,);
        loading.value = false
        tableData.value = res.data
        total.value = res.totalCount
    })
}

const onChangeDate = (params) => { 
    searchForm.value.operDate = transformWorkTime(params,orgStartTime,orgEndTime)  
}

onChangeDate('今天')

getTableData()

// 点击退款
let form = ref({})
let max = ref()
let visible_return = ref(false)
const handleReturn = (row) => {
    console.log('row', row)
    max.value = Number(row.canRefundFee)
    form.value = row
    // form.value.refundFee = Number(form.value.payMoney)
    visible_return.value = true
}

const handleSubCode = (v)=> {
      if(unpay.value !== undefined) {
        console.log(v,'dasdasdaxxxxxxx')
        Api.Common.PcObjProcess.Do({ "functionName": "AggregatePayPrice", "orgCode": "0004", "contentData": {"TradeNo":v.tradeNo} }).then(res => {
        console.log('退款 AggregatePayPrice :>> ', res,);
        if(Number(res.remainingMoney) >= Number(unpay.value) ){
            emit("emitconsumeCode", v.tradeNo);
            emit('emitCancel', 'cancel')
        } else {
            ElNotification({
            title: '提示',
            message: '金额过小，剩余金额' + res.remainingMoney,
            type: 'warning',
        })
        }
    })

   
      } else {
        emit("emitconsumeCode", v.tradeNo);
        emit('emitCancel', 'cancel')
      }
} 

const submitloading = ref(false)
const handleSubmit = (params) => {
    if (!form.value.refundFee || form.value.refundFee == 0) return ElNotification({
        title: '提示',
        message: '请输入退款金额',
        type: 'warning',
    })
    const data = {
        TradeNo: form.value.tradeNo,
        PayType: form.value.payType,
        RefundFee: form.value.refundFee,
        PayMoney: form.value.payMoney,
        Remark: form.value.remark
    }
    console.log('调用退款接口前的data :>> ', data);
    submitloading.value = true
    // return
    Api.Common.PcObjProcess.Do({ "functionName": "Refund", "orgCode": "0004", "contentData": data }).then(res => {
        console.log('退款 res :>> ', res,);
        ElNotification({
            title: '提示',
            message: '退款成功',
            type: 'success',
        })
        submitloading.value = false
        form.value = {}
        visible_return.value = false
        getTableData()
    })
}
const handleCancel = (params) => {
    form.value = {}
    visible_return.value = false
}

// 取消
const emit = defineEmits(['emitCancel', 'emitSubmit','emitconsumeCode'])
const handleCancelDialog = (params) => {
    emit('emitCancel', 'cancel')
}

</script>

<style scoped lang="scss">
@import '@/styles/com_style_input.css';
/* 在这里编写组件的CSS样式 */
.dialog-box {
    ::v-deep {
        .el-dialog {
            width: 1300px !important;
            border-radius: 16px;
        }
    }

    .my-header {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        gap: 16px;

        .close-btn {
            width: 100px;
            height: 48px;
            background: #CCCCCC;
            border-radius: 8px;
        }
    }
}

.app-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 100%;
    padding: 20px 100px 0px 100px;
    background: #F2F2F2;

    .table-info-row {
        width: 1220px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .table-info {
            font-family: Microsoft YaHei;
            font-weight: bold;
            font-size: 20px;
            color: #212121;
            line-height: 100px;
        }

        .back-btn {
            width: 120px;
            height: 60px;
            background: #CCCCCC;
            border-radius: 8px;
            font-size: 18px;
            color: #212121;
            border: 0px;
        }
    }

    .content-box {
        margin-top: 20px;
        display: flex;
    }
}

.search-form {
    // width: 1220px;
    background: #FFFFFF;
    border-radius: 8px;
    padding: 20px 10px 0 40px;
    margin-bottom: 20px;

    // display: flex;
    .search-form-item {
        ::v-deep {
            .el-form-item__label {
                line-height: 48px;
                width: 90px;
            }

            .el-date-editor {
                // width: 240px;

            }

            .el-input__wrapper {
                width: 180px;
                height: 48px;
                background: #FFFFFF;
                border-radius: 8px;
            }

            .el-select__wrapper {
                width: 180px;
                height: 48px;
                background: #FFFFFF;
                border-radius: 8px;
            }
            .el-range-editor.el-input__wrapper{
                width: 360px;
            }
           
        }
    }

    .range-item {
        .el-input {
            width: 166px;
        }
    }

    .action-btn-box {
        float: right;
        margin-right: 42px;
        button {
            width: 120px;
            height: 40px;
            line-height: 40px;
            background: #FFE566;
            border-radius: 8px;
            border: 0;
            font-size: 16px;
            color: #212121;
        }

        .reset-btn {
            background: #E6E6E6;
            color: #666666;
        }
    }
}
.table-box {
    padding: 20px 40px;
    background: #FFFFFF;
    border-radius: 8px;
    width: 1220px;

    .total-box {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        font-size: 20px;
        color: #212121;
    }
    .el-table--fit {
         height: 400px;
    }

    ::v-deep {
        .el-table__inner-wrapper::before {
            height: 0px;
        }

        .el-table th {
            font-size: 13px;
            font-weight: 700;
        }

        .el-table .el-table__header th,
        .el-table .el-table__header tr,
        .el-table .el-table__header td {
            height: 48px;
            background: #F9F9F9;
        }
    }

    .action-btn {
        width: 66px;
        height: 28px;
        border-radius: 4px;
        border: 1px solid #FF6A00;
        font-family: Microsoft YaHei;
        font-weight: 400;
        font-size: 14px;
        color: #FF6A00;
    }
}

.pagination-box {
    margin-top: 20px;

    ::v-deep {
        .number {
            background: #E6E6E6 !important;
            border-radius: 8px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            font-size: 18px;
            color: #666666;
        }

        .number:hover {
            color: #FF6A00;
        }

        .is-active {
            background-color: #FF6A00 !important;
            border-radius: 8px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            font-size: 18px;
            color: #FFFFFF;
        }

    }
}

.color-FF6A00 {
    color: #FF6A00;
}


.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;

    .close-btn {
        width: 100px;
        height: 48px;
        background: #CCCCCC;
        border-radius: 8px;
    }
}

.class-form {
    margin-top: 20px;
}

.footer-box {
    margin-top: 20px;
    display: flex;
    justify-content: center;

    .cancel {
        width: 160px;
        height: 60px;
        background: #FFFFFF;
        border-radius: 8px;
        border: 1px solid #FF6A00;
        font-size: 24px;
        color: #FF6A00;
    }

    .submit {
        width: 160px;
        height: 60px;
        background: #FF6A00;
        border-radius: 8px;
        font-size: 24px;
        color: #FFFFFF;
        margin-left: 30px;
    }
}

.return-dialog {
    ::v-deep {
        .el-dialog {
            width: 500px !important;
        }
    }
}
</style>
  